package henu.action;

import henu.bean.BusinessMessage;
import henu.bean.Car;
import henu.bean.DrivingCar;
import henu.bean.ManagePerson;
import henu.bean.PInformation;
import henu.dao.DrivingCarDao;
import henu.dao.ManagePersonDao;
import henu.dao.factory.DaoFactory;
import henu.util.AJAX;
import henu.util.CONSTANTS;
import henu.util.Page;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DrivingCarAction extends ActionSupport {
	private DrivingCar dc = new DrivingCar();
	private File photo; // 上传的文件
	private String photoFileName; // 文件名称
	private String url;// 转发地址
	private String message;// 提示消息
	AJAX ajax;
	private String uid;

	// 文件测试
	private String name;

	// 上传多个文件的集合文本

	private List<File> upload;
	// /多个上传文件的类型集合
	private List<String> uploadContentType;
	// 多个上传文件的文件名集合
	private List<String> uploadFileName;

	public String getName() {
		return name;
	}

	public void setName(String name) {

		this.name = name;
	}

	public List<File> getUpload() {

		return upload;
	}

	public void setUpload(List<File> upload) {

		this.upload = upload;
	}

	public List<String> getUploadContentType() {

		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadContentType) {

		this.uploadContentType = uploadContentType;
	}

	public List<String> getUploadFileName() {

		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadFileName) {

		this.uploadFileName = uploadFileName;
	}

	// 文件测试
	// 查询条件
	private String property = "-1";
	private String key = "-1";
	private String sort;
	private int start;
	private int end;

	// 接收所有数据
	private List<DrivingCar> list = null;
	// 分页排序
	private Page page = new Page();
	private int pageNum = 1;
	private int numPerPage = 10;
	private String orderField = "drid";
	private String orderDirection = "asc";
	private String args;// 接收idcard用于删除

	public DrivingCar getDc() {
		return dc;
	}

	public void setDc(DrivingCar dc) {
		this.dc = dc;
	}

	public File getPhoto() {
		return photo;
	}

	public void setPhoto(File photo) {
		this.photo = photo;
	}

	public String getPhotoFileName() {
		return photoFileName;
	}

	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}

	public String getUrl() {
		return url;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getEnd() {
		return end;
	}

	public void setEnd(int end) {
		this.end = end;
	}

	public List<DrivingCar> getList() {
		return list;
	}

	public void setList(List<DrivingCar> list) {
		this.list = list;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	public String getOrderField() {
		return orderField;
	}

	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}

	public String getOrderDirection() {
		return orderDirection;
	}

	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}

	public String getArgs() {
		return args;
	}

	public void setArgs(String args) {
		this.args = args;
	}

	public AJAX getAjax() {
		return ajax;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String add() throws Exception {
		/* 先根据身份证号和车牌号从车辆信息表中找出该车辆的信息 */
		ajax = new AJAX();
		PInformation p = (PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
		Car c = DaoFactory.getDrivingCarDaoInstance().findByIdCardAndVehicleLicense(p.getIdCard(),dc.getVehicleLicense());
		// 如果c为空说明车辆信息不完全
		if (c == null) {
			ajax.setStatusCode("300");
			ajax.setMessage("请完善车辆信息后再来完成行车证信息");
		}else{
			// 根据车牌号和行车证号判断行车证信息是否添加
			DrivingCar dca = DaoFactory.getDrivingCarDaoInstance().findByDrivingIdOrVehicleLicense(dc.getDrivingId(),dc.getVehicleLicense());
			if(dca != null){
				ajax.setStatusCode("300");
				ajax.setMessage("你已经添加过行车证信息");
			}else{
				//文件上传
				String path = ServletActionContext.getServletContext().getRealPath("/upload/drivingCarImages");
				// 写到指定的路径中
				File file = new File(path);
				// 如果指定的路径没有就创建
				if (!file.exists()) {
					file.mkdirs();
				}
				// 把得到的文件的集合通过循环的方式读取并放在指定的路径下
				for (int i = 0; i < upload.size(); i++) {
					try{
						String fileName = dc.getCarid()	+ uploadFileName.get(i).substring(uploadFileName.get(i).lastIndexOf("."));// 系统时间+后缀
						FileUtils.copyFile(upload.get(i), new File(file,fileName));
						dc.setCopyDrivingCar("upload/drivingCarImages/"	+ fileName);
					}catch (IOException e) {
						e.printStackTrace();
					}
				}
				dc.setCarid(c.getCarid());
				int result = DaoFactory.getDrivingCarDaoInstance().add(dc);
				if (result != 0) {
					ajax.setStatusCode("200");
					ajax.setMessage("添加成功");
					ajax.setCallbackType("closeCurrent");
					ajax.setNavTabId("drivingCarInfos");
				} else {
					ajax.setStatusCode("300");
					ajax.setMessage("添加失败，请重新填写");
				}
			}
		}
		url = "/front/ajax.jsp";
		return SUCCESS;

	}

	public String adminDelete() throws Exception {
		DrivingCarDao dao = DaoFactory.getDrivingCarDaoInstance();
		int result = dao.deleteById(Integer.parseInt(uid));
		ajax = new AJAX();
		if (result != 0) {
			ajax.setStatusCode("200");
			ajax.setMessage("删除成功");
			ajax.setNavTabId("adminDrivingCarInfo");
			ajax.setCallbackType("");

		} else {
			ajax.setStatusCode("300");
			ajax.setMessage("删除失败");
		}
		url = "/admin/ajax.jsp";
		return SUCCESS;
	} 
	public String delete() throws Exception {
		DrivingCarDao dao = DaoFactory.getDrivingCarDaoInstance();
		int result = dao.deleteById(Integer.parseInt(uid));
		ajax = new AJAX();
		if (result != 0) {
			ajax.setStatusCode("200");
			ajax.setMessage("删除成功");
			ajax.setNavTabId("drivingCarInfos");
			ajax.setCallbackType("");

		} else {
			ajax.setStatusCode("300");
			ajax.setMessage("删除失败");
		}
		url = "/front/ajax.jsp";
		return SUCCESS;
	}

	public String find() throws Exception {
		DrivingCarDao dao = DaoFactory.getDrivingCarDaoInstance();
		DrivingCar d = dao.findById(Integer.parseInt(uid));
		ActionContext.getContext().put("drivingCar", d);
		url = "/front/drivingCarUpdate.jsp";
		return SUCCESS;
	}

	// 根据身份证号找到carid，再车carid找到行车证
	public String findAllByCarId() throws Exception {
		page = new Page();
		if (orderField.equals("") || orderDirection.equals("")) {
			orderField = "drid";
			orderDirection = "asc";
		}
		if (property.equals("") || key.equals("")) {
			property = "-1";
			key = "-1";
		}
		// 直接查询条数,表比较多，所以直接用sql查询降低难度

		PInformation p = (PInformation) ServletActionContext.getRequest()
				.getSession().getAttribute(CONSTANTS.SESSION_PERSON);
		page.setSql(
				"select count(*) from drivingcar dc,carinformation c where "
						+ property + "='" + key + "' and c.userid='"
						+ p.getIdCard() + "' and c.carid=dc.carid", pageNum,
				numPerPage);
		list = DaoFactory.getDrivingCarDaoInstance().findAllByCarId(property,
				key, p.getIdCard(), orderField, orderDirection,
				page.getStart(), page.getEnd());
		url = "/front/drivingCarManage.jsp";
		return SUCCESS;
	}

	public String update() throws Exception {
		ajax = new AJAX();
		// 文件上传
		String path = ServletActionContext.getServletContext().getRealPath(
				"/upload/drivingCarImages");
		System.out.println(path);
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		for (int i = 0; i < upload.size(); i++) {
			try {
				String fileName = dc.getCarid()
						+ uploadFileName.get(i).substring(
								uploadFileName.get(i).lastIndexOf("."));// 系统时间+后缀
				FileUtils.copyFile(upload.get(i), new File(file, fileName));
				dc.setCopyDrivingCar("upload/drivingCarImages/" + fileName);

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		DrivingCarDao dao = DaoFactory.getDrivingCarDaoInstance();
		int result = dao.update(Integer.parseInt(uid), dc);
		if (result != 0) {
			System.out.println(result + "2");
			ajax.setStatusCode("200");
			ajax.setMessage("更新成功");
			ajax.setCallbackType("closeCurrent");
			ajax.setNavTabId("drivingCarInfos");

		} else {
			ajax.setStatusCode("300");
			ajax.setMessage("更新失败");
			System.out.println(result + "3");
		}
		url = "/front/ajax.jsp";
		return SUCCESS;
	}

	// 前台用户根据id查看一条信息
	public String detail() throws Exception {

		dc = DaoFactory.getDrivingCarDaoInstance().findById(
				Integer.parseInt(uid));
		url = "/front/drivingCarDetail.jsp";
		return SUCCESS;
	}
	//根据管理员所在的公司的comid，根据comid找到从carinformation中carid，根据carid从drivingCar找到行车证
	public String findAllByComid() throws Exception {
		page=new Page();
		if(orderField.equals("")||orderDirection.equals("")){
			orderField="businessId";
			orderDirection="asc";
		}
		if(property.equals("")||key.equals("")){
			property="-1";
			key="-1";
		}
	//直接查询条数,表比较多，所以直接用sql查询降低难度
		ManagePerson m=(ManagePerson) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_ADMIN);
		page.setSql("select count(*) from drivingcar d,carinformation c where "+property+"='"+key+"' and c.comid='"+m.getComid()+"' and c.carid=d.carid",pageNum,numPerPage);
		list=DaoFactory.getDrivingCarDaoInstance().findAllByComid(property, 
				key, m.getComid(), orderField, orderDirection, page.getStart(), page.getEnd());
		url="/admin/drivingCarManage.jsp";
		return SUCCESS;
	}
	public String findAll() throws Exception {
		page = new Page();
		if (orderField.equals("") || orderDirection.equals("")) {
			orderField = "drid";
			orderDirection = "asc";
		}
		if (property.equals("") || key.equals("")) {
			property = "-1";
			key = "-1";
		}
		page.setProperties("DrivingCar", pageNum, numPerPage, property, key);

		list = DaoFactory.getDrivingCarDaoInstance()
				.findByProperty(property, key, orderField, orderDirection,
						page.getStart(), page.getEnd());
		url = "/admin/drivingCarManage.jsp";
		return SUCCESS;
	}

	public String findAllBefore() throws Exception {
		page = new Page();
		if (orderField.equals("") || orderDirection.equals("")) {
			orderField = "drid";
			orderDirection = "asc";
		}
		if (property.equals("") || key.equals("")) {
			property = "-1";
			key = "-1";
		}
		page.setProperties("DrivingCar", pageNum, numPerPage, property, key);

		list = DaoFactory.getDrivingCarDaoInstance()
				.findByProperty(property, key, orderField, orderDirection,
						page.getStart(), page.getEnd());
		url = "/front/drivingCarManage.jsp";
		return SUCCESS;
	}

	private void HandleMsg(String statusCode, String msg, String tabid,
			String callback) {
		ajax = new AJAX();
		ajax.setCallbackType(callback);
		ajax.setMessage(msg);
		ajax.setStatusCode(statusCode);
		ajax.setNavTabId("drivingCarInfos");

	}
}
